import logging
import multiprocessing
from logging.handlers import QueueHandler, QueueListener

def worker_process(queue):
    logger = logging.getLogger()
    logger.setLevel(logging.INFO)
    logger.addHandler(QueueHandler(queue))  # 发送日志到队列
    
    logger.info(f"Worker {multiprocessing.current_process().name} started")

def logger_process(queue):
    handler = logging.FileHandler("app.log")
    formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(message)s")
    handler.setFormatter(formatter)
    
    listener = QueueListener(queue, handler)
    listener.start()
    try:
        # 持续监听队列，直到收到停止信号
        while True:
            pass
    except KeyboardInterrupt:
        pass
    finally:
        listener.stop()

if __name__ == "__main__":
    queue = multiprocessing.Queue()
    
    # 启动日志进程
    logger_p = multiprocessing.Process(target=logger_process, args=(queue,))
    logger_p.daemon = True
    logger_p.start()
    
    # 启动工作进程
    workers = [multiprocessing.Process(target=worker_process, args=(queue,)) for _ in range(3)]
    for w in workers:
        w.start()
    for w in workers:
        w.join()
    
    # 所有工作进程结束后，停止日志进程
    queue.put(None)
    logger_p.join()